<template>
  <div class="article">
    <MainTabBar
      :editableTabs="editableTabs"
      :editable-tabs-value="editableTabsValue"
      @tabHandleClick="tabHandleClick"
      @removeTab="removeTab"
    >
    </MainTabBar>
    <div class="text">
      <div style="width: 700px; margin-top: 20px" v-if="tabType == 1">
        <el-form
          :model="form"
          ref="form"
          label-width="100px"
          class="demo-ruleForm"
          :rules="rules"
        >
          <el-form-item label="标题" prop="title">
            <el-input
              type="age"
              v-model.trim="form.name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="封面图片" prop="cover_img">
            <el-upload
              class="avatar-uploader"
              :action="action"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" alt />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
              
            <div class="image_operate">
              <el-button size="mini" type="primary" @click="deleteImage" v-if="deleteImageType">删除图片</el-button>
              <div class="deleteImageBut">
              <ChooseImg @cliUrl="cliUrl" />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="文章分类" prop="cate_id">
            <el-select
              v-model="form.cate_id"
              placeholder="请选择活动区域"
              style="width: 100%"
            >
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="(item, index) in cateList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
           <el-form-item label="发布时间">
             <el-date-picker
              v-model="pub_date"
              align="right"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions">
            </el-date-picker>
           </el-form-item>
          <el-form-item label="文章编辑">
            <el-button type="primary" @click="drawer = true"
              >打开编辑器</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="resetForm" v-if="submitFormType == 0">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-else-if="tabType == 0" >
        <div>
          <el-button class="btn" @click="addArticleCate">添加</el-button>
        </div>
        <TableComp
          :table-data="tableData"
          :table-column="tableColumn"
          :modifyType="false"
          @modifyRow="modifyRow"
          @deleteRow="deleteRow"
        ></TableComp>
      </div>
    </div>
    <!-- <el-button @click="sendBolg">发送</el-button> -->
    <el-drawer
      title="富文本编辑器"
      :visible.sync="drawer"
      direction="btt"
      :before-close="handleClose"
      size="95%"
    >
      <mavon-editor v-model="context" :toolbars="toolbars" />
    </el-drawer>
  </div>
</template>
<script>
import Api from "../../api/api";
import request from "../../api/request";
import TableComp from "../../common/manage/TableComp.vue";
import MainTabBar from "../../common/manage/MainTabBar.vue";
import ChooseImg from "../../common/manage/chooseIMG.vue"
import qs from "qs";
export default {
  components: {
    TableComp,
    MainTabBar,
    ChooseImg,
  },
  data() {
    return {
      context: " ", //输入的数据
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        mark: true, // 标记
        superscript: true, // 上角标
        quote: true, // 引用
        htmlcode: true, // 展示html源码
        ol: true, // 有序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        help: true, // 帮助
        code: true, // code
        subfield: true, // 是否需要分栏
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        undo: true, // 上一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        navigation: true, // 导航目录
      },
      imageUrl:"",
      action: "",
      headers: {},
      tableData: [],
      tab: "",
      deleteImageType : false,
      tableColumn: [
        {
          label: "名称",
          prop: "name",
        },
        {
          label: "发布时间",
          prop: "pub_date",
        },
        {
          label: "文章分类",
          prop:"cate",
        },
        {
          label: "发布者",
          prop:"author_name",
        },
      ],
      editableTabs: [
        {
          title: "文章列表",
          name: "0",
          closable: false,
        },
      ],
      editableTabsValue: "0",
      tabIndex: 0,
      form: {},
      rules: {
        // name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
        // alias: [{ required: true, message: "请输入分类别名", trigger: "blur" }],
      },
      tabType: 0, //标签类型，0为表格显示，1为增加或修改页面
      submitFormType: 0, //保存的类型，0为新增，1为修改
      cateList: [],
      drawer: false,
      userList:null,
      pub_date:'',
      pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
    };
  },
  mounted() {
    this.getArticleCateData();
    this.getArticleData();
    this.action = Api.uploads;
    // this.headers.Authorization = this.$store.state.token
    this.headers.Authorization = window.localStorage.token
    this.headers.fileUrl = 'article'
    console.log();
  },
  
  methods: {
    // 用户头像上传
    handleAvatarSuccess(res, file) {
      this.deleteImageType = true
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.cover_img = res.imgSrc;
      console.log(1,this.form);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG / png格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    cliUrl(item){
      this.imageUrl =Api.API_HEADER+item
      this.form.cover_img = item
    },
    deleteImage(){
       let params = {
        method: "POST",
        url: Api.deleteUploads,
        data: qs.stringify({fileurl:this.form.cover_img}),
      };
      request(params)
        .then((result) => {
          if (result.status == 3) {
            this.$message.error("用户登录失效");
            this.$router.push({ name: "bolgHome" });
          } else if (result.status == 0) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.imageUrl = ""
            this.deleteImageType = false
          }
        })
        .catch((err) => {
        });
    },
    // 打开弹出框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 逻辑代码
    // 获取文章分类
    getArticleCateData() {
      let params = {
        method: "GET",
        url: Api.getArticleCate,
      };
      request(params)
        .then((result) => {
          if (result.status == 3) {
            this.$message.error("用户登录失效");
            this.$router.push({ name: "bolgHome" });
          } else if (result.status == 0) {
            this.cateList = result.data;
            this.getUserData();
          }
        })
        .catch((err) => {
        });
    },
    //获取文章
    getArticleData(){
      let params = {
        method: "GET",
        url: Api.getArticle,
      };
      request(params)
        .then((result) => {
          if (result.status == 3) {
            this.$message.error("用户登录失效");
            this.$router.push({ name: "bolgHome" });
          } else if (result.status == 0) {
            this.tableData = result.data;
            this.tableData.forEach(item => {
              this.cateList.forEach(item2 => {
                if(item.cate_id == item2.id){
                  item.cate = item2.name 
                }
              })
              this.userList.forEach(item2 => {
                if(item.author_id == item2.id){
                  item.author_name = item2.nickname
                }
              })
            })
            
          }
          
        })
        .catch((err) => {
        });
    },
    //获取用户列表
    getUserData(){
      let params = {
        method: "GET",
        url: Api.getUserList,
      };
      request(params)
        .then((result) => {
          if (result.status == 3) {
            this.$message.error("用户登录失效");
            this.$router.push({ name: "bolgHome" });
          } else if (result.status == 0) {
            this.userList = result.data;
          }
        })
        .catch((err) => {
        });
    },
    tabHandleClick(tabs) {
      let name = tabs.name;
      this.editableTabsValue = tabs.name;
      let tab;
      this.editableTabs.forEach((item) => {
        if (item.name == name) {
          tab = item;
        }
      });
      if (tab.name == 0) {
        this.tabType = 0;
      } else {
        this.tabType = 1;
        if (!tab.row) {
          this.submitFormType = 0;
          this.form = {};
        } else {
          this.submitFormType = 1;
          this.form = tab.row;
        }
      }
    },
    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter((tab) => tab.name !== targetName);
      if (this.editableTabs.length == 1) {
        this.tabType = 0;
      }
    },
    modifyRow(row) {
      for (let i = 0; i < this.editableTabs.length; i++) {
        if (this.editableTabs[i].title.indexOf(row.name) >= 0) {
          return;
        }
      }
      let newTabName = ++this.tabIndex + "";
      let obj = {
        title: row.name + "-修改",
        name: newTabName,
        closable: true,
        row: row,
      };
      this.editableTabs.push(obj);
      this.tabType = 1;
      this.form = row;
      this.submitFormType = 1;
      this.editableTabsValue = newTabName;
    },
    deleteRow(row) {
      let id = Number(row.id);
      let params = {
        method: "POST",
        url: Api.deleteArticle + "/" + id,
        // data:qs.stringify({id})
      };
      request(params)
        .then((result) => {
          if (result.status == 3) {
            this.$message.error("用户登录失效");
            this.$router.push({ name: "bolgHome" });
          } else if (result.status == 0) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getArticleData()
          } else {
            this.$message.error("删除失败");
          }
        })
        .catch((err) => {
        });
    },
    addArticleCate() {
      for (let i = 0; i < this.editableTabs.length; i++) {
        if (this.editableTabs[i].title == "新增") {
          return;
        }
      }
      let newTabName = ++this.tabIndex + "";
      let obj = {
        title: "新增",
        name: newTabName,
        closable: true,
      };
      this.editableTabs.push(obj);
      this.form = {};
      this.tabType = 1;
      this.submitFormType = 0;
      this.editableTabsValue = newTabName;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.submitFormType == 0) {
            this.addArticleCateData();
          } else if (this.submitFormType == 1) {
            this.modifyArticleCateData();
          }
        } else {
          return false;
        }
      });
    },
    addArticleCateData() {
      this.form.content = this.converter.makeHtml(this.context);
      let pub_date 
      if(this.pub_date == ''){
        pub_date = new Date()
      }else{
        pub_date = this.pub_date
      }
      let { name,cover_img, content,cate_id } = this.form;
      console.log(cover_img);
      let author_id = this.$store.state.userInfo.id
      let params = {
        method: "POST",
        url: Api.addArticle,
        data: qs.stringify({ name, cate_id, cover_img, content,pub_date,author_id}),
      };
      request(params)
        .then((result) => {
          if (result.status == 3) {
            this.$message.error("用户登录失效");
            this.$router.push({ name: "bolgHome" });
          } else if (result.status == 0) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.getArticleCateData();
            this.removeTab(this.targetName)
          } else {
            this.$message.error("添加失败");
          }
        })
        .catch((err) => {
        });
    },
    modifyArticleCateData() {
      let { name, alias, id } = this.form;
      let params = {
        method: "POST",
        url: Api.modifyArticleCate,
        data: qs.stringify({ id, name, alias }),
      };
      request(params)
        .then((result) => {
          if (result.status == 3) {
            this.$message.error("用户登录失效");
            this.$router.push({ name: "bolgHome" });
          } else if (result.status == 0) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.getArticleCateData();
          } else {
            this.$message.error("修改失败");
          }
        })
        .catch((err) => {
        });
    },
    resetForm() {
      this.form = {};
    },
  },
};
</script>
<style lang="scss" scoped>
.article{
  width: 100%;
  height: 100%;
  .text {
    padding: 20px;
    .btn {
      background-color: #545c64;
      color: #fff;
    }
  }
}
.el-tabs__nav .el-tabs__item:nth-child(1) span {
  display: none;
}
.image_operate{
  float: left;
  .deleteImageBut{
  margin-right: 20px;
  float: left;    
}
}

</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 90px;
  height: 90px;
  line-height: 90px !important;
  text-align: center;
}
.avatar {
  width: 90px;
  height: 90px;
  display: block;
}

</style> 